import { useEffect, useRef, useState } from "react";
import {
  Card,
  Col,
  Divider,
  Empty,
  FloatButton,
  Row,
  Spin,
  Tooltip,
  Typography,
  Table,
  Space,
} from "antd";
import {
  ArrowUpOutlined,
  DownloadOutlined,
  HeartOutlined,
  StarOutlined,
} from "@ant-design/icons";
import { movieServiceApi, statisticsServiceApi } from "@/api";
import DownMovieModal from "@/components/business/downMovieDetail";
import { handleDownload, isEmptyArray } from "@/utils";
import { ChangeShowMovieType } from "@/types/changeShowMovie";
import styles from "./index.module.less";
const { Text, Paragraph } = Typography;
const { Meta } = Card;

const MovieList = (props) => {
  const { movies, loading, currentShowType } = props;
  const [showBackTop, setShowBackTop] = useState(false);
  const [movieDetail, setMovieDetail] = useState(null);

  const downloadModalRef = useRef(null);

  const downloadMovie = async (movie) => {
    const result = await movieServiceApi.getDownloadUrl(movie.id);
    if (result.code === 200 && !isEmptyArray(result.data)) {
      // 判断是否需要直接下载
      if (result.data.length === 1) {
        statisticsServiceApi.updateDownLoadMovieById(result.data[0].movieId);
        handleDownload(result.data[0].href);
        return;
      }
      setMovieDetail({
        ...movie,
        downloadUrls: result.data,
      });
      downloadModalRef.current.showDownloadModal(true);
    }
  };

  const toDetail = (movie) => {
    const url = window.location.origin + "/movie/detail/" + movie.id;
    window.open(url, "_blank");
  };

  const columns = [
    {
      title: "电影名称",
      dataIndex: "title",
      key: "title",
      render: (_, record) => (
        <div className={styles.movieTitle}>
          <Tooltip title={record.title} color="rgba(255, 255, 255)">
            <span className={styles.truncateTitle}>{record.title}</span>
          </Tooltip>
        </div>
      ),
    },
    {
      title: "电影简介",
      dataIndex: "introduction",
      key: "introduction",
      render: (_, record) => (
        <Paragraph className={styles.movieIntroduction}>
          {record.introduction}
        </Paragraph>
      ),
    },
    {
      title: "操作",
      key: "action",
      fixed: "right",
      width: 150,
      render: (_, record) => (
        <Space size="middle">
          <span
            style={{ color: "#00BC7D", cursor: "pointer" }}
            onClick={(event) => {
              event?.stopPropagation();
              toDetail(record);
            }}
          >
            详情
          </span>
          <span
            style={{ color: "#00BC7D", cursor: "pointer" }}
            onClick={(event) => {
              event?.stopPropagation();
              downloadMovie(record);
            }}
          >
            下载
          </span>
        </Space>
      ),
    },
  ];

  // 监听滚动事件，控制回到顶部按钮显示/隐藏
  useEffect(() => {
    const handleScroll = () => {
      // 当页面滚动超过300px时显示回到顶部按钮
      setShowBackTop(window.scrollY > 300);
    };

    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  return (
    <>
      <div className={styles.moviePage}>
        <div style={{ marginTop: "24px", marginBottom: "12px" }}></div>
        {/* 页面内容 */}
        <div className={styles.content}>
          {/* 电影卡片网格 */}
          {loading ? (
            <div className={styles.loadingContainer}>
              <Spin size="large" tip="加载中..." />
            </div>
          ) : movies?.length === 0 ? (
            <Empty
              description="暂无电影数据"
              className={styles.emptyContainer}
            />
          ) : currentShowType === ChangeShowMovieType.ViewGridCard ? (
            <Row gutter={[16, 16]}>
              {movies?.map((movie) => (
                <Col
                  xs={24}
                  sm={12}
                  md={8}
                  lg={6}
                  key={movie.id}
                  style={{ cursor: "pointer" }}
                  onClick={() => {
                    toDetail(movie);
                  }}
                >
                  <Card
                    hoverable
                    cover={
                      <img
                        alt={movie.title}
                        src={movie.cover}
                        className={styles.movieCover}
                      />
                    }
                    actions={[
                      <span
                        onClick={(event) => {
                          event?.stopPropagation();
                          // statisticsServiceApi.updateLikeMovieById(movie.id);
                        }}
                        style={{
                          display: "inline-block",
                          justifyContent: "center",
                          alignItems: "center",
                        }}
                      >
                        <span style={{marginRight:'4px'}}>点赞</span>
                        <HeartOutlined key="like" />
                      </span>,
                      <DownloadOutlined
                        key="download"
                        onClick={(event) => {
                          event?.stopPropagation();
                          downloadMovie(movie);
                        }}
                      />,
                    ]}
                    className={styles.movieCard}
                  >
                    <Meta
                      title={
                        <div className={styles.movieTitle}>
                          <Tooltip
                            title={movie.title}
                            color="rgba(255, 255, 255)"
                          >
                            <span className={styles.truncateTitle}>
                              {movie.title}
                            </span>
                          </Tooltip>
                          <Text type="secondary" className={styles.movieYear}>
                            {movie.publisthTime}
                          </Text>
                        </div>
                      }
                      description={
                        <div>
                          <div className={styles.movieRating}>
                            <Text strong>{movie.rating}</Text>
                          </div>
                          <Tooltip
                            color="rgba(255, 255, 255)"
                            title={movie.introduction}
                            overlayClassName={styles.introductionTooltip}
                          >
                            <Paragraph
                              ellipsis={{ rows: 2 }}
                              className={styles.movieDesc}
                            >
                              {movie.introduction}
                            </Paragraph>
                          </Tooltip>
                        </div>
                      }
                    />
                  </Card>
                </Col>
              ))}
            </Row>
          ) : (
            <Card>
              <Table
                columns={columns}
                dataSource={movies}
                pagination={false}
                bordered
              />
            </Card>
          )}
        </div>

        {/* 回到顶部按钮 */}
        <FloatButton.BackTop
          tooltip={{
            title: "回到顶部",
            color: "#fff",
            placement: "top",
          }}
          icon={<ArrowUpOutlined key="up" />}
          className={styles.backTop}
          visibilityHeight={300}
          style={{
            display: showBackTop ? "block" : "none",
          }}
        ></FloatButton.BackTop>
      </div>
      <DownMovieModal ref={downloadModalRef} movieDetail={movieDetail} />
    </>
  );
};

export default MovieList;
